using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Security;
using DomainModel.Abstract;
using DomainModel.Entities;

namespace WebSite.Controllers
{
    [Authorize(Roles="Applicant")]
    public class ApplicationController : Controller
    {
        private IApplicationsRepository applicationRepository;
        private IEducationsRepository educationsRepository;
        private IPersonalReferencesRepository referencesRepository;
        private IPositionsRepository positionsRepository;
        private IJobHistoriesRepository jobhistoryRepository;
        private IJobsRepository jobsRepository;
        private IApplicantsProgressRepository applicantsProgressRepository;
        private IStoresRepository storesRepository;

        Guid UserID = (Guid)Membership.GetUser().ProviderUserKey;

        public ApplicationController(IApplicationsRepository applicationsRepository, 
                                        IEducationsRepository educationsRepository, 
                                        IPersonalReferencesRepository personalreferenceRepository, 
                                        IJobHistoriesRepository jobhistoryrepository,
                                        IPositionsRepository positionsRepository,
                                        IJobsRepository jobsRepository,
                                        IApplicantsProgressRepository applicantsProgressRepository,
                                        IStoresRepository storesRepository)
        {
            this.applicationRepository = applicationsRepository;
            this.educationsRepository = educationsRepository;
            this.referencesRepository = personalreferenceRepository;
            this.jobhistoryRepository = jobhistoryrepository;
            this.positionsRepository = positionsRepository;
            this.jobsRepository = jobsRepository;
            this.applicantsProgressRepository = applicantsProgressRepository;
            this.storesRepository = storesRepository;

            TempData["error"] = "";
        }

        class JobPosition
        {
            public string JobTitle { get; set; }
            public int PositionID { get; set; }
        }

        private Job GetJob(int jobID)
        {
            Job job = (from j in jobsRepository.Jobs
                       where j.JobID == jobID
                       select j).First();
            return job;
        }

        private Store GetStore(int storeID)
        {
            Store store = (from s in storesRepository.Stores
                       where s.StoreID == storeID
                       select s).First();
            return store;
        }

        // This is just a wrapper for the query to get a position given an id.
        private Position GetPosition(int? positionID)
        {
            Position position = (from p in positionsRepository.Positions
                                 where p.PositionID == positionID
                                 select p).First();
            return position;
        }

        // This is just a wrapper for the query to get a application given an id.
        private Application GetApplication(int ApplicationID)
        {
            Application application = (from j in applicationRepository.Applications
                       where j.ApplicationID == ApplicationID
                       select j).First();

            return application;
        }

        // Provides list of applications in repository as model to Index view.
        public ViewResult Index()
        {
            Application application = null;
            try
            {
                application = (from j in applicationRepository.Applications
                               where j.UserID == UserID
                               select j).First();
            }
            catch (Exception) { }

            if (application == null)
            {
                return View(new Application());
            }
            else
            {
                return View(application);
            }
        }
 

        // Edit command for http get, returns a application given an id
        // and passes the application to the view.
        [AcceptVerbs(HttpVerbs.Get)]
        public ViewResult Edit(int ApplicationId)
        {
            List<JobPosition> positions = new List<JobPosition>();
            positions.Add(new JobPosition { PositionID = 0, JobTitle = "Select a position" });
            foreach (Position p in positionsRepository.Positions)
                if (p.Filled == 0)
                {
                    string jobTitle = GetJob(p.JobID).JobTitle;
                    jobTitle += " at store ";
                    jobTitle += GetStore(p.StoreID).Name;
                    positions.Add(new JobPosition { PositionID = p.PositionID, JobTitle = jobTitle });
                }

            var position1list = new SelectList(positions, "PositionID", "JobTitle");
            var position2list = new SelectList(positions, "PositionID", "JobTitle");
            var position3list = new SelectList(positions, "PositionID", "JobTitle");


            ViewData["position1list"] = position1list;
            ViewData["position2list"] = position2list;
            ViewData["position3list"] = position3list;

            bool exists = false;
            foreach (Application a in applicationRepository.Applications)
                if (a.ApplicationID == ApplicationId)
                    exists = true;
            if ( ! exists)
                return View("Edit", new Application());

            Application application = GetApplication(ApplicationId);

            return View(application);
        }

        // Edit command for post, places a application from the view into
        // the repository.
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Application application)
        {
            var position1 = System.Int32.Parse(Request.Form["Position1DropDown"]);
            var position2 = System.Int32.Parse(Request.Form["Position2DropDown"]);
            var position3 = System.Int32.Parse(Request.Form["Position3DropDown"]);

            application.Position1 = position1;

            if (position2 == 0)
                application.Position2 = null;
            else
                application.Position2 = position2;

            if (position3 == 0)
                application.Position3 = null;
            else
                application.Position3 = position2;            

            foreach (ApplicantProgress ap in applicantsProgressRepository.ApplicantsProgress)
                if (ap.ApplicationID == application.ApplicationID)
                    applicantsProgressRepository.DeleteApplicantProgress(ap);

            application.UserID = UserID;
            applicationRepository.SaveApplication(application);

            ApplicantProgress applicantProgress = new ApplicantProgress();
            applicantProgress.ApplicationID = application.ApplicationID;
            applicantProgress.HadPhoneInterview = false;
            applicantProgress.HadPhysicalInterview = false;
            applicantProgress.PassedPhoneInterview = false;
            applicantProgress.PassedPhysicalInterview = false;

            applicantsProgressRepository.SaveApplicantProgress(applicantProgress);

            return RedirectToAction("Education", "Application");
        }

        // This deletes a job from the repository given a
        // id from the view.
        public RedirectToRouteResult Delete(int applicationID)
        {
            Application application = GetApplication(applicationID);
            applicationRepository.DeleteApplication(application);

            return RedirectToAction("Index");
        }


        //Education view and post
        public ViewResult Positions()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Positions(Application application, string submitButton)
        {
            IQueryable<Application> Applications = (from j in applicationRepository.Applications
                                                    where j.UserID == UserID
                                                    select j);
            
            return RedirectToAction("Index", "Application");
        }

        //Education view and post
        public ViewResult Education()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Education(Education education, string submitButton)
        {
            IQueryable<Application> Applications = (from j in applicationRepository.Applications
                                                    where j.UserID == UserID
                                                    select j);
            education.ApplicationID = Applications.First().ApplicationID;

            switch (submitButton)
            {
                case "Add More Education":
                    educationsRepository.SaveEducation(education);
                    return RedirectToAction("Education", "Application");
                case "Submit Education":
                    educationsRepository.SaveEducation(education);
                    return RedirectToAction("References", "Application");
                case "Skip Education":
                    return RedirectToAction("References", "Application");
            }
            return RedirectToAction("Index", "Application");   
        }

        //References view and post
        public ViewResult References()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult References(PersonalReference reference, string submitButton)
        {
            IQueryable<Application> Applications = (from j in applicationRepository.Applications
                                                    where j.UserID == UserID
                                                    select j);
            reference.ApplicationID = Applications.First().ApplicationID;

            switch (submitButton)
            {
                case "Add More References":
                    referencesRepository.SavePersonalReference(reference);
                    return RedirectToAction("References", "Application");
                case "Submit References":
                    referencesRepository.SavePersonalReference(reference);
                    return RedirectToAction("JobHistory", "Application");
                case "Skip References":
                    return RedirectToAction("JobHistory", "Application");
            }
            return RedirectToAction("Index", "Application");
        }

        //Job History view and post
        public ViewResult JobHistory()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult JobHistory(JobHistory jobhistory, string submitButton)
        {
            IQueryable<Application> Applications = (from j in applicationRepository.Applications
                                                    where j.UserID == UserID
                                                    select j);
            jobhistory.ApplicationID = Applications.First().ApplicationID;

            switch (submitButton)
            {
                case "Add More Job Histories":
                    jobhistoryRepository.SaveJobHistory(jobhistory);
                    return RedirectToAction("JobHistory", "Application");
                case "Submit Job Histories":
                    jobhistoryRepository.SaveJobHistory(jobhistory);
                    return RedirectToAction("Questionnaire", "Questionnaire");
                case "Skip Job Histories":
                    return RedirectToAction("Questionnaire", "Questionnaire");
            }
            return RedirectToAction("Index", "Application");
        }
    }
}
